﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Fuyao.Business.Entities.Models;
using Fuyao.Business.Logic.BC;
using System.Drawing;

namespace Fuyao.Win.UI.Util
{
    public class Utilitarios
    {
        public static BusinessLogic bc = new BusinessLogic();
        public static int _contadorDePuntos = 0;

        public static void limpiarControles(Form frm)
        {
            foreach (TextBox txt in frm.Controls.OfType<TextBox>()) txt.Text = String.Empty;
            foreach (ComboBox cbo in frm.Controls.OfType<ComboBox>())
            {
                if (cbo.DataSource != null) cbo.SelectedIndex = 0;
            }
        }

        public static void desabilitaControles(Panel pnl)
        {
            foreach (TextBox txt in pnl.Controls.OfType<TextBox>())
            {
                txt.ReadOnly = true;
                txt.BackColor = Color.White;
                txt.ForeColor = Color.Black;
            }            
        }

        #region No se usa
        /*public static string validarDatosStringEmpty(Panel pnl, ErrorProvider _errPrv, ref bool isValid)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("Ingrese los campos requeridos: " + System.Environment.NewLine);

            for (int i = pnl.Controls.Count - 1; i >= 0; i--)
            {
                if (pnl.Controls[i] is TextBox)
                {
                    var txt = pnl.Controls[i];
                    if (txt != null)
                    {
                        if (txt.Text == string.Empty && txt.Tag != null)
                        {
                            sb.Append("- " + txt.Tag + System.Environment.NewLine);
                            _errPrv.SetError(txt, "Ingrese el " + txt.Tag);
                            isValid = false;
                        }
                    }
                }
            }
            if (!isValid) return sb.ToString();
            else return string.Empty;
        }*/
        #endregion

        public static string FormatoPrecio(Double valor)
        {
            return valor.ToString("####0.00");
        }

        public static void cargarCboPerfiles(ComboBox cbo)
        {
            List<Perfil> listPerfil = new List<Perfil>();
            listPerfil = bc.getPerfil();
            if (listPerfil.Count > 0)
            {
                var sqlPerfil = (from lst in listPerfil
                                 select new { lst.PerfilID, lst.DescripcionPerfil }).ToList();

                cbo.DataSource = sqlPerfil;
                cbo.ValueMember = "PerfilID";
                cbo.DisplayMember = "DescripcionPerfil";
                cbo.SelectedIndex = 0;
            }
        }

        public static void cargarCboVendedores(ComboBox cbo)
        {
            List<Vendedor> listVendedor = new List<Vendedor>();
            #region LLenaParamentrosEntidad
            Vendedor beVendedor = new Vendedor();
            beVendedor.NombreVendedor = "0";
            beVendedor.ApellidoVendedor = "0";
            beVendedor.Estado = true;
            #endregion

            listVendedor = bc.getVendedorByFilter(beVendedor);
            if (listVendedor.Count > 0)
            {
                List<Vendedor> _listVend = new List<Vendedor>();
                Vendedor beVend = new Vendedor();
                beVend.VendedorID = 0;
                beVend.NombreVendedor = "<-- SELECCIONE UN VENDEDOR -->";
                _listVend.Add(beVend);
                _listVend.AddRange(listVendedor);

                var sqlVendedor = (from lst in _listVend
                                   select new { lst.VendedorID, NombreVendedor = (lst.NombreVendedor + ' ' + lst.ApellidoVendedor).Trim() }).ToList();

                cbo.DataSource = sqlVendedor;
                cbo.ValueMember = "VendedorID";
                cbo.DisplayMember = "NombreVendedor";
                cbo.SelectedIndex = 0;
            }
        }

        public static void cargarCategoriaProducto(ComboBox cbo)
        {
            List<Producto> listProducto = new List<Producto>();
            listProducto = bc.getCategoriaProducto();
            if (listProducto.Count > 0)
            {
                List<Producto> _listCategoriaProducto = new List<Producto>();
                Producto beVend = new Producto();
                beVend.CategoriaAuto = "<-- SELECCIONE UN MODELO -->";
                _listCategoriaProducto.Add(beVend);
                _listCategoriaProducto.AddRange(listProducto);

                var sqlVendedor = (from lst in _listCategoriaProducto
                                   select new { lst.CategoriaAuto }).ToList();

                cbo.DataSource = sqlVendedor;
                cbo.ValueMember = "CategoriaAuto";
                cbo.DisplayMember = "CategoriaAuto";
                cbo.SelectedIndex = 0;
            }
        }


        public static void cargarCboConductor(ComboBox cbo)
        {
            List<Conductor> listConductor = new List<Conductor>();
            #region LLenaParamentrosEntidad
            Conductor beConductor = new Conductor();
            beConductor.NombreConductor = "0";
            beConductor.ApellidoConductor = "0";
            beConductor.LicenciaConducir = "0";
            beConductor.Estado = true;
            #endregion

            listConductor = bc.getConductorByFilter(beConductor);
            if (listConductor.Count > 0)
            {
                List<Conductor> _listCond = new List<Conductor>();
                Conductor beCond = new Conductor();
                beCond.ConductorID = 0;
                beCond.NombreConductor = "<-- SELECCIONE UN CONDUCTOR -->";
                _listCond.Add(beCond);
                _listCond.AddRange(listConductor);

                var sqlConductor = (from lst in _listCond
                                   select new { lst.ConductorID, NombreConductor = (lst.NombreConductor + ' ' + lst.ApellidoConductor).Trim() }).ToList();

                cbo.DataSource = sqlConductor;
                cbo.ValueMember = "ConductorID";
                cbo.DisplayMember = "NombreConductor";
                cbo.SelectedIndex = 0;
            }
        }

        public static void cargarCboEstadosParametrosTable(ComboBox cbo,string tableName)
        {
            List<Parametro> listParametro = new List<Parametro>();
            listParametro = bc.getParametroList();
            if (listParametro.Count > 0)
            {
                var sqlEstadoParametro = (from lst in listParametro
                                        where lst.TableName == tableName
                                        select new { lst.Valor, lst.Nombre }).ToList();

                cbo.DataSource = sqlEstadoParametro;
                cbo.ValueMember = "Valor";
                cbo.DisplayMember = "Nombre";
                if (sqlEstadoParametro.Count > 0)
                    cbo.SelectedIndex = 0;
            }
        }

        public static void cargarCboFacturaTipoMoneda(ComboBox cbo)
        {
            List<Parametro> listParametro = new List<Parametro>();
            listParametro = bc.getParametroList();
            if (listParametro.Count > 0)
            {
                var sqlFacturaTipoMoneda = (from lst in listParametro
                                            where lst.TableName == "FACTURA_MONEDA"
                                            select new { lst.Valor, lst.Nombre }).ToList();


                cbo.DataSource = sqlFacturaTipoMoneda;
                cbo.ValueMember = "Valor";
                cbo.DisplayMember = "Nombre";
                if (sqlFacturaTipoMoneda.Count > 0)
                    cbo.SelectedIndex = 0;
            }
        }

        public static void cargarCboDepartamento(ComboBox cbo)
        {
            List<Departamento> listDepartamento = new List<Departamento>();
            listDepartamento = bc.getAllDepartamentos();
            if (listDepartamento.Count > 0)
            {
                List<Departamento> _listNew = new List<Departamento>();
                Departamento beDept = new Departamento();
                beDept.DepartamentoID = 0;
                beDept.Departamento1 = "<-- SELECCIONE UN DEPARTAMENTO -->";
                _listNew.Add(beDept);
                _listNew.AddRange(listDepartamento);

                cbo.DataSource = _listNew;
                cbo.ValueMember = "DepartamentoID";
                cbo.DisplayMember = "Departamento1";
                if (_listNew.Count > 0)
                    cbo.SelectedIndex = 0;
            }
        }

        public static void cargarCboProvincia(ComboBox cbo,int DepartamentoID)
        {
            List<Provincia> listProvincia = new List<Provincia>();
            listProvincia = bc.getAllProvinciaByDepartamentoID(DepartamentoID);
            if (listProvincia.Count > 0)
            {
                List<Provincia> _listNew = new List<Provincia>();
                Provincia beProv = new Provincia();
                beProv.ProvinciaID = 0;
                beProv.Provincia1 = "<-- SELECCIONE UNA PROVINCIA -->";
                _listNew.Add(beProv);
                _listNew.AddRange(listProvincia);

                cbo.DataSource = _listNew;
                cbo.ValueMember = "ProvinciaID";
                cbo.DisplayMember = "Provincia1";
                if (_listNew.Count > 0)
                    cbo.SelectedIndex = 0;
            }
        }

        public static void cargarCboDistrito(ComboBox cbo, int ProvinciaID)
        {
            List<Distrito> listDistrito = new List<Distrito>();
            listDistrito = bc.getAllDistritosByProvinciaID(ProvinciaID);
            if (listDistrito.Count > 0)
            {
                List<Distrito> _listNew = new List<Distrito>();
                Distrito beDist = new Distrito();
                beDist.DistritoID = 0;
                beDist.Distrito1 = "<-- SELECCIONE UN DISTRITO -->";
                _listNew.Add(beDist);
                _listNew.AddRange(listDistrito);

                cbo.DataSource = _listNew;
                cbo.ValueMember = "DistritoID";
                cbo.DisplayMember = "Distrito1";
                if (_listNew.Count > 0)
                    cbo.SelectedIndex = 0;
            }
        }

        public static string getNombreFrm(string nameForm)
        {
            string[] cadenas = nameForm.Split('.');
            return cadenas[cadenas.Length - 1];
        }

        public static void vSoloNumeros(KeyPressEventArgs e)
        {
            if (Char.IsDigit(e.KeyChar) || Char.IsControl(e.KeyChar)) e.Handled = false;
            else e.Handled = true;
        }

        public static void cerrarFormularioEscape(KeyPressEventArgs e, Form frm)
        {
            if (e.KeyChar == Convert.ToChar(Keys.Escape)) frm.Close();
        }

        public static void configurarGrilla(ref DataGridView dgv, bool fromList = false)
        {
            dgv.BackgroundColor = Color.WhiteSmoke;
            dgv.AutoGenerateColumns = false;
            dgv.AllowUserToAddRows = false;
            dgv.BackgroundColor = Color.WhiteSmoke;
            dgv.RowTemplate.Resizable = DataGridViewTriState.False;
            if (fromList)
                dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        }

        public static void vPrecio(KeyPressEventArgs e)
        {
            if (Char.IsNumber(e.KeyChar)) e.Handled = false;
            else if (Char.IsControl(e.KeyChar))
            {
                e.Handled = false;
                resetPuntos();
            }
            else if (Char.IsPunctuation(e.KeyChar))
            {
                if (e.KeyChar.ToString() == ".")
                {
                    e.Handled = false;
                    SetsumaPuntos();
                    if (getsumaPuntos() > 1) e.Handled = true;
                }
                else e.Handled = true;
            }
            else e.Handled = true;
        }

        public static void resetPuntos()
        {
            _contadorDePuntos = 0;
        }

        public static int getsumaPuntos()
        {
            return _contadorDePuntos;
        }

        public static void SetsumaPuntos()
        {
            _contadorDePuntos += 1;
        }

        public static System.Boolean IsNumeric(System.Object Expression)
        {
            if (Expression == null || Expression is DateTime)
                return false;

            if (Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
                return true;

            try
            {
                if (Expression is string)
                    Double.Parse(Expression as string);
                else
                    Double.Parse(Expression.ToString());
                return true;
            }
            catch { } // just dismiss errors but return false
            return false;
        }

        public static System.Object IsNumericWithReturnValue(System.Object Expression)
        {
            if (Expression == null || Expression is DateTime)
                return 0;

            if (Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
                return Expression;

            try
            {
                if (Expression is string)
                    Double.Parse(Expression as string);
                else
                    Double.Parse(Expression.ToString());
                return Expression;
            }
            catch { } // just dismiss errors but return false
            return 0;
        }

        private delegate void SetNextColumnIndex(int columnIndex, DataGridView dgv);

        private static void SetCustomNextColumnIndex(int columnIndex, DataGridView dgv)
        {
            dgv.CurrentCell = dgv.CurrentRow.Cells[columnIndex];
            dgv.BeginEdit(true);
        }

        public static void SetNextCellFocus(DataGridView dgv, int nextIndex = 0)
        {
            if (nextIndex == 0)
            {
                nextIndex = Math.Min(dgv.Columns.Count - 1, dgv.CurrentCell.ColumnIndex + 1);
            }

            SetNextColumnIndex method = new SetNextColumnIndex(SetCustomNextColumnIndex);
            object[] parameters = new object[2];
            parameters[0] = nextIndex;
            parameters[1] = dgv;
            dgv.BeginInvoke(method, parameters);
        }

    }
}
